package com.meiyuetao.myt.sale.web.action;

import java.util.Date;
import java.util.List;
import java.util.Map;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.exception.DataAccessDeniedException;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.security.AclService;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.util.DateUtils;
import lab.s2jh.core.web.annotation.SecurityControlIgnore;
import lab.s2jh.core.web.view.OperationResult;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;

import com.google.common.collect.Lists;
import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.job.BusinessNotifyService;
import com.meiyuetao.myt.partner.entity.Partner;
import com.meiyuetao.myt.purchase.entity.PurchaseOrder;
import com.meiyuetao.myt.purchase.entity.PurchaseReceipt;
import com.meiyuetao.myt.sale.entity.BoxOrder;
import com.meiyuetao.myt.sale.entity.BoxOrder.BoxOrderStatusEnum;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail.BoxOrderDetailStatusEnum;
import com.meiyuetao.myt.sale.entity.BoxOrderDetailCommodity;
import com.meiyuetao.myt.sale.entity.SaleDelivery;
import com.meiyuetao.myt.sale.service.BoxOrderDetailService;
import com.meiyuetao.myt.sale.service.BoxOrderService;

@MetaData("BoxOrderDetailController")
public class BoxOrderDetailController extends MytBaseController<BoxOrderDetail, Long> {

    @Autowired
    private BoxOrderService boxOrderService;
    @Autowired
    private BoxOrderDetailService boxOrderDetailService;
    @Autowired
    private AclService aclService;
    @Autowired
    private BusinessNotifyService businessNotifyService;

    @Override
    protected BaseService<BoxOrderDetail, Long> getEntityService() {
        return boxOrderDetailService;
    }

    @Override
    protected void setupDetachedBindingEntity(Long id) {
        bindingEntity = getEntityService().findDetachedOne(id, "boxOrderDetailCommodities");
    }

    public HttpHeaders getEarlyWarningList() {
        // 待提醒用户付款的订单行项
        GroupPropertyFilter groupFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupFilter.append(new PropertyFilter(MatchType.LE, "reserveDeliveryTime", new DateTime().plusDays(8).toDate()));
        groupFilter.append(new PropertyFilter(MatchType.IN, "orderDetailStatus", new BoxOrderDetailStatusEnum[] { BoxOrderDetailStatusEnum.S10O, BoxOrderDetailStatusEnum.S15O }));
        List<BoxOrderDetail> boxOrderDetails = boxOrderDetailService.findByFilters(groupFilter);
        setModel(buildPageResultFromList(boxOrderDetails));
        return buildDefaultHttpHeaders();
    }

    @Override
    protected void checkEntityAclPermission(BoxOrderDetail entity) {
        // 限定只能访问登录用户所在商家的数据
        String aclCodePrefix = aclService.getLogonUserAclCodePrefix();
        Partner agentPartner = entity.getBoxOrder().getAgentPartner();
        if (agentPartner != null && StringUtils.isNotBlank(aclCodePrefix)) {
            String agentPartnerCode = agentPartner.getCode();
            if (!agentPartnerCode.startsWith(aclCodePrefix)) {
                throw new DataAccessDeniedException();
            }
        }
    }

    @Override
    protected void appendFilterProperty(GroupPropertyFilter groupPropertyFilter) {
        // 限定只能访问登录用户所在商家的数据
        String aclCodePrefix = aclService.getLogonUserAclCodePrefix();
        if (StringUtils.isNotBlank(aclCodePrefix)) {
            groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.BW, "boxOrder.agentPartner.code", aclCodePrefix));
        }
    }

    @Override
    @MetaData("保存")
    public HttpHeaders doSave() {
        return super.doSave();
    }

    @Override
    @MetaData("查询")
    public HttpHeaders findByPage() {
        return super.findByPage();
    }

    @MetaData("保存")
    public HttpHeaders modifyPrice() {
        boxOrderDetailService.modifyPrice(bindingEntity);
        setModel(OperationResult.buildSuccessResult("订单行项改价成功"));
        return buildDefaultHttpHeaders();
    }

    @MetaData(value = "订单行项商品列表")
    public HttpHeaders boxOrderDetailCommodities() {
        List<BoxOrderDetailCommodity> boxOrderDetailCommodities = bindingEntity.getBoxOrderDetailCommodities();
        setModel(buildPageResultFromList(boxOrderDetailCommodities));
        return buildDefaultHttpHeaders();
    }

    @MetaData(value = "日程统计数据")
    @SecurityControlIgnore
    public HttpHeaders events() {
        // 基于FullCalendar日程组件获取查询区间段参数
        Date start = DateUtils.parseDate(getRequiredParameter("start"));
        Date end = DateUtils.parseDate(getRequiredParameter("end"));

        String aclCodePrefix = aclService.getLogonUserAclCodePrefix();

        List<Map<String, Object>> events = Lists.newArrayList();
        GroupPropertyFilter groupPropertyFilter = null;
        Page<Map<String, Object>> datas = null;

        if (StringUtils.isBlank(aclCodePrefix)) {

            groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
            groupPropertyFilter.append(new PropertyFilter(MatchType.GE, "voucherDate", start));
            groupPropertyFilter.append(new PropertyFilter(MatchType.LE, "voucherDate", end));
            groupPropertyFilter.append(new PropertyFilter(MatchType.NU, "redwordDate", true));
            datas = getEntityService().findByGroupAggregate(SaleDelivery.class, groupPropertyFilter, null, "voucherDate", "count(voucherDate) as count");
            for (Map<String, Object> data : datas.getContent()) {
                data.put("title", "销售单数<span class='pull-right'>" + data.get("count") + "</span>");
                data.put("start", DateUtils.formatDate((Date) data.get("voucherDate")));
                data.put("backgroundColor", "#3cc051");
                events.add(data);
            }

            groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
            groupPropertyFilter.append(new PropertyFilter(MatchType.GE, "voucherDate", start));
            groupPropertyFilter.append(new PropertyFilter(MatchType.LE, "voucherDate", end));
            groupPropertyFilter.append(new PropertyFilter(MatchType.NU, "redwordDate", true));

            datas = getEntityService().findByGroupAggregate(PurchaseReceipt.class, groupPropertyFilter, null, "voucherDate", "count(voucherDate) as count");
            for (Map<String, Object> data : datas.getContent()) {
                data.put("title", "收货入库单数<span class='pull-right'>" + data.get("count") + "</span>");
                data.put("start", DateUtils.formatDate((Date) data.get("voucherDate")));
                data.put("backgroundColor", "#69a4e0");
                events.add(data);
            }

            groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
            groupPropertyFilter.append(new PropertyFilter(MatchType.GE, "voucherDate", start));
            groupPropertyFilter.append(new PropertyFilter(MatchType.LE, "voucherDate", end));
            groupPropertyFilter.append(new PropertyFilter(MatchType.NU, "redwordDate", true));

            datas = getEntityService().findByGroupAggregate(PurchaseOrder.class, groupPropertyFilter, null, "voucherDate", "count(voucherDate) as count");
            for (Map<String, Object> data : datas.getContent()) {
                data.put("title", "采购订单数<span class='pull-right'>" + data.get("count") + "</span>");
                data.put("start", DateUtils.formatDate((Date) data.get("voucherDate")));
                data.put("backgroundColor", "#428bca");
                events.add(data);
            }
        }

        groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.GE, "reserveDeliveryTime", start));
        groupPropertyFilter.append(new PropertyFilter(MatchType.LE, "reserveDeliveryTime", end));
        groupPropertyFilter.append(new PropertyFilter(MatchType.IN, "orderDetailStatus", new BoxOrderDetailStatusEnum[] { BoxOrderDetailStatusEnum.S15O,
                BoxOrderDetailStatusEnum.S20PYD, BoxOrderDetailStatusEnum.S25PYD, BoxOrderDetailStatusEnum.S30C, BoxOrderDetailStatusEnum.S35C, BoxOrderDetailStatusEnum.S40DP }));
        if (StringUtils.isNotBlank(aclCodePrefix)) {
            groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.BW, "boxOrder.agentPartner.code", aclCodePrefix));
        }
        datas = getEntityService().findByGroupAggregate(BoxOrderDetail.class, groupPropertyFilter, null, "reserveDeliveryTime", "count(reserveDeliveryTime) as count");
        for (Map<String, Object> data : datas.getContent()) {
            data.put("title", "预约发货单数<span class='pull-right'>" + data.get("count") + "</span>");
            data.put("start", DateUtils.formatDate((Date) data.get("reserveDeliveryTime")));
            data.put("backgroundColor", "#ed4e2a");
            events.add(data);
        }

        groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.GE, "orderTimeDate", start));
        groupPropertyFilter.append(new PropertyFilter(MatchType.LE, "orderTimeDate", end));
        groupPropertyFilter.append(new PropertyFilter(MatchType.NE, "orderStatus", BoxOrderStatusEnum.S90CANCLE));
        if (StringUtils.isNotBlank(aclCodePrefix)) {
            groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.BW, "agentPartner.code", aclCodePrefix));
        }
        datas = getEntityService().findByGroupAggregate(BoxOrder.class, groupPropertyFilter, null, "orderTimeDate", "count(orderTimeDate) as count");
        for (Map<String, Object> data : datas.getContent()) {
            data.put("title", "销售订单数<span class='pull-right'>" + data.get("count") + "</span>");
            data.put("start", data.get("orderTimeDate"));
            data.put("backgroundColor", "#fcb322");
            events.add(data);
        }

        setModel(events);
        return buildDefaultHttpHeaders();
    }

    @Override
    public HttpHeaders revisionList() {
        return super.revisionList();
    }

    @Override
    public HttpHeaders revisionCompare() {
        return super.revisionCompare();
    }

    @MetaData("行项收货完成操作")
    public HttpHeaders recvConfirm() {

        boxOrderDetailService.recvConfirm(bindingEntity);
        setModel(OperationResult.buildSuccessResult("订单行项收货完成"));
        return buildDefaultHttpHeaders();
    }

    @MetaData("行项完结操作")
    public HttpHeaders successClose() {
        // Validation.isTrue(bindingEntity.getDeliveryFinishTime() != null,
        // "订单行项还未完成收货");
        boxOrderDetailService.successClose(bindingEntity);
        setModel(OperationResult.buildSuccessResult("订单行项完结成功"));
        return buildDefaultHttpHeaders();
    }

}